<template>
  <view :class="ns.b()" :ref="editorRef">
    <uni-rate v-model="currentVal" :disabled="disabled || readonly" :max="max" @change="handleChange" />
  </view>
</template>
<script lang="ts">
export default {
  options: {
    addGlobalClass: true,
    virtualHost: true,
    styleIsolation: "shared"
  }
}
</script>
<script lang="ts" setup>
  import { getEditorEmits, getRateProps } from "@/props";
  import { useFocusAndBlur, useNamespace } from "@/use";
  import { toNumber } from "lodash-es";
  import { ref, watch } from "vue";
  import { RateEditorController } from "./i-biz-rate.controller";

  const props = defineProps(getRateProps<RateEditorController>());
  const emit = defineEmits();
  const ns = useNamespace("rate");
  // 当前值
  const currentVal = ref<number>();

  const c = props.controller;

  const editorModel = c.model;

  // 设置允许的最大值
  let max = 5;
  if (editorModel.editorParams) {
    if (editorModel.editorParams.maxValue) {
      max = toNumber(editorModel.editorParams.maxValue);
    }
  }

  watch(
    () => props.value,
    (newVal, oldVal) => {
      if (newVal !== oldVal) {
        if (!newVal) {
          currentVal.value = 0;
        } else {
          currentVal.value = newVal as number;
        }
      }
    },
    { immediate: true }
  );

  const handleChange = (event: IData) => {
    emit("change", event.value);
  };

  // 聚焦失焦事件
  const { componentRef: editorRef } = useFocusAndBlur(
    () => emit("focus"),
    () => emit("blur")
  );
</script>
<style lang="scss">
  .ibiz-rate {
    .uni-rate {
      float: getCssVar(form-item-container, editor-align);
    }
  }
</style>
